import Vue from 'vue'
import Router from 'vue-router';
import config from '@/common/config.js';

// 解决多次点击重复路由报错
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
	return originalPush.call(this, location).catch(err => err)
}

Vue.use(Router);

const router = new Router({
	mode: 'hash',
	//解决路由跳转页面没有置顶
	scrollBehavior(to, from, savedPosition) {
		if (savedPosition) {
			return savedPosition
		} else {
			return {
				x: 0,
				y: 0
			}
		}
	},
	// !!注意: 二级路由不需要加 '/'
	routes: config.routerRoutes
});

//路由守卫
router.beforeEach((to, from, next) => {
	//解决三级路由不缓存的问题
	if (to.matched && to.matched.length > 2) {
		for (let i = 0; i < to.matched.length; i++) {
			const element = to.matched[i]
			if (element.components.default.name === 'blank') { //三级组件公共组件的name
				//console.log("to.matched.splice之前", to.matched);
				to.matched.splice(i, 1);
				//console.log("to.matched.splice之后", to.matched);
			}
		}
	}
	config.routerBeforeEach(to, from, next);
});

export default router
